package com.leyou.auth.service.impl;

import com.leyou.auth.constants.JwtConstants;
import com.leyou.auth.dto.Payload;
import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.List;

import static com.leyou.auth.constants.JwtConstants.REDIS_KEY;

@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            //检测用户名或密码是否为空
            if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
                throw new LyException(400,"用户名或密码不能为空");
            }

            UserDTO userDTO = userClient.queryInfo(username, password);
            //判断数据库中是否有该用户
            if(userDTO==null){
                throw new LyException(400,"用户名或密码错误");
            }

            String jwt = jwtUtils.createJwt(UserDetail.of(userDTO.getId(), userDTO.getUsername()));

            writCookie(response,jwt);
        } catch (FeignException e) {
            // 把远程调用异常转换抛出
            throw new LyException(e.status(), e.contentUTF8());
        }

    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        try {
            String token = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
            Payload payload = jwtUtils.parseJwt(token);
            String key = REDIS_KEY + payload.getUserDetail().getUsername();
            redisTemplate.delete(key);
        } catch (Exception e) {
        }

        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, "");

        cookie.setDomain(JwtConstants.DOMAIN);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        cookie.setHttpOnly(true);

        response.addCookie(cookie);
    }

    private void writCookie(HttpServletResponse response,String token){
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, token);
        //设置cookie的作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        //是否禁止JS操作cookie，避免xss攻击
        cookie.setHttpOnly(true);
        //cookie有效期，-1就是跟随当前会话，浏览器关闭就消失
        cookie.setMaxAge(-1);
        //cookie作用的路径，/代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }
}
